package com.cwd.arm.domain.repository.impl;

import com.cwd.arm.domain.entity.ProjectEntity;
import com.cwd.arm.domain.repository.ProjectRepository;
import com.cwd.arm.infrastructure.dao.PayDao;
import com.cwd.arm.infrastructure.po.PayPo;
import com.cwd.arm.domain.entity.PayEntity;
import com.cwd.arm.domain.repository.PayRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
* Description:现金支出
* Created on 2021年11月20日
* @author  yan
*/
@Repository
public class PayRepositoryImpl implements PayRepository{

    @Autowired
    private PayDao dao;

    @Autowired
    private ProjectRepository projectRepository;

    @Override
    public void save(PayEntity payEntity) {
        dao.save(convertToPayPo(payEntity));
        ProjectEntity projectEntity = projectRepository.buildProjectEntity(payEntity.getProjectId());
        projectRepository.addPay(projectEntity, payEntity);
    }

    @Override
    public void update(PayEntity payEntity) {
        PayEntity oldPayEntity = buildPayEntity(payEntity.getId());
        dao.updateById(convertToPayPo(payEntity));
        ProjectEntity projectEntity = projectRepository.buildProjectEntity(oldPayEntity.getProjectId());
        projectRepository.updatePay(projectEntity, oldPayEntity,payEntity);
    }

    @Override
    public void del(Long id) {
        PayEntity payEntity = buildPayEntity(id);
        dao.removeById(id);
        ProjectEntity projectEntity = projectRepository.buildProjectEntity(payEntity.getProjectId());
        projectRepository.delPay(projectEntity,payEntity);
    }

    private PayPo convertToPayPo(PayEntity entity){
        PayPo PayPo = new PayPo();
        BeanUtils.copyProperties(entity,PayPo);
        return PayPo;
    }


    private PayEntity buildPayEntity(Long id){
        PayPo payPo = dao.getById(id);
        return convertToPayEntity(payPo);
    }

    private PayEntity convertToPayEntity(PayPo payPo){
        PayEntity payEntity = new PayEntity();
        BeanUtils.copyProperties(payPo,payEntity);
        return payEntity;
    }


}
